package rad.framework.conv;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import javax.persistence.EntityManager;

import rad.framework.jpa.TransactionScript;
import rad.framework.lang.ReflectionUtil;

public abstract class ImportCommand<E> extends BaseCommand {

	protected boolean oneFile = false;

	public ImportCommand(String persistenceUnitJndiName) {
		super(persistenceUnitJndiName);
	}

	public void execute() throws Exception {
		new TransactionScript(persistenceUnitJndiName) {
			@SuppressWarnings("unchecked")
			@Override
			protected Object run(EntityManager em) {
				Object o = transform();
				if (o instanceof List) {
					List<E> list = (List<E>) o;
					for (E e : list) {
						em.merge(e);
					}
				} else {
					em.merge(o);
				}
				return null;
			}
		}.run();
	}

	protected abstract Object transform();

	protected InputStream getXml() {
		try {
			return new FileInputStream(getFileName());
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	protected Class<E> getEntityClass() {
		return ReflectionUtil.getParameterizedType(getClass());
	}
	
	protected String getEntityName() {
		return getEntityClass().getSimpleName();
	}
}
